import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/backstage/toolkit/utilities/app_constants.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/toolkit/widgets/common_utils.dart';
import 'package:thal/backstage/toolkit/widgets/stage_whisper.dart';
import 'package:thal/playbill/main_feature/main_production.dart';

part 'settings_production.page.dart';

/// 设置页面
@PagePath('/settings')
class SettingsProduction extends StatefulWidget {
  const SettingsProduction({super.key});

  @pageRouteQuery
  static RouteQuery query() => const _$SettingsProductionQuery().call();

  @override
  State<SettingsProduction> createState() => _SettingsProductionState();
}

class _SettingsProductionState extends State<SettingsProduction> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(AssetManifest.screenBackground),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _generateHeader(context),

              20.h.heightBox,

              // 设置选项列表
              Expanded(child: _generateSettingsList(context)),
            ],
          ),
        ),
      ),
    );
  }

  /// 生成顶部导航栏
  Widget _generateHeader(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: ColorPalette.white.withValues(alpha: 0.5),
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.chevron_left_rounded,
                color: ColorPalette.black,
                size: 36.sp,
              ),
            ),
          ),
          Expanded(
            child: Center(
              child: Text('Set Up')
                  .fontSize(28.sp)
                  .textColor(ColorPalette.black)
                  .carterOne(weight: FontWeight.w700),
            ),
          ),
          36.w.widthBox,
        ],
      ),
    );
  }

  /// 生成设置列表
  Widget _generateSettingsList(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          // Privacy Policy
          _generateMenuItem(
            context,
            title: 'Privacy Policy',
            onTap: () {
              CommonUtils.launchUrl(ProjectConstants.privacyPolicyUrl);
            },
          ),

          16.h.heightBox,

          // Terms Of Service
          _generateMenuItem(
            context,
            title: 'Terms Of Service',
            onTap: () {
              CommonUtils.launchUrl(ProjectConstants.termsOfServiceUrl);
            },
          ),

          16.h.heightBox,

          // Delete Account
          _generateMenuItem(
            context,
            title: 'Delete Account',
            onTap: () {
              _handleDeleteAccount(context);
            },
          ),

          60.h.heightBox,

          // Log Out按钮
          _generateLogoutButton(context),
        ],
      ),
    );
  }

  /// 生成菜单项
  Widget _generateMenuItem(
    BuildContext context, {
    required String title,
    required VoidCallback onTap,
  }) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 18.h),
        decoration: BoxDecoration(
          color: ColorPalette.white,
          borderRadius: BorderRadius.circular(20.r),
        ),
        child: Row(
          children: [
            Text(title)
                .fontSize(16.sp)
                .textColor(ColorPalette.black)
                .arimo(weight: FontWeight.w500),
            const Spacer(),
            Icon(
              Icons.chevron_right_rounded,
              color: ColorPalette.black,
              size: 24.sp,
            ),
          ],
        ),
      ).withTapEffect(onTap: onTap),
    );
  }

  /// 生成Logout按钮
  Widget _generateLogoutButton(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.symmetric(vertical: 16.h),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [ColorPalette.blue2, ColorPalette.blue1],
          ),
          borderRadius: BorderRadius.circular(30.r),
        ),
        child: Text('Log Out', textAlign: TextAlign.center)
            .fontSize(20.sp)
            .textColor(ColorPalette.white)
            .arimo(weight: FontWeight.w700),
      ).withTapEffect(
        onTap: () {
          _handleLogout(context);
        },
      ),
    );
  }

  /// 处理删除账号
  void _handleDeleteAccount(BuildContext context) {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            backgroundColor: ColorPalette.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(20.r),
            ),
            title: Text('Delete Account')
                .fontSize(20.sp)
                .textColor(ColorPalette.black)
                .arimo(weight: FontWeight.w600),
            content:
                Text(
                      'Are you sure you want to delete your account? This action cannot be undone.',
                    )
                    .fontSize(14.sp)
                    .textColor(ColorPalette.black.withValues(alpha: 0.7))
                    .arimo(),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: Text('Cancel')
                    .fontSize(16.sp)
                    .textColor(ColorPalette.iconGrey)
                    .arimo(weight: FontWeight.w500),
              ),
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  _performDeleteAccount(context);
                },
                child: Text('Confirm')
                    .fontSize(16.sp)
                    .textColor(ColorPalette.red)
                    .arimo(weight: FontWeight.w600),
              ),
            ],
          ),
    );
  }

  /// 执行删除账号操作
  void _performDeleteAccount(BuildContext context) {
    final userRoom = GlobalStateProvider.userRoomOf(context);

    // 实际上执行的是退出登录
    userRoom.performLogout();

    // 提示删除成功
    StageWhisper.cheer('Account deleted successfully!');

    context.router.replace(MainProduction.query());
  }

  /// 处理Logout操作
  void _handleLogout(BuildContext context) {
    final userRoom = GlobalStateProvider.userRoomOf(context);

    // 执行退出登录
    userRoom.performLogout();

    // 提示退出成功
    StageWhisper.cheer('Logged out successfully');

    context.router.replace(MainProduction.query());
  }
}
